<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="资产ID" prop="assetId">
        <el-input
          v-model="queryParams.assetId"
          placeholder="请输入资产ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属种植区" prop="plantAreaId">
        <el-select v-model="queryParams.plantAreaId" placeholder="请选择所属种植区">
          <el-option
            v-for="item in plantArea"
            :key="item.plantAreaId"
            :label="item.plantAreaName"
            :value="item.plantAreaId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="assetCategory">
        <el-select v-model="queryParams.assetCategory" placeholder="请选择分类" clearable>
          <el-option
            v-for="dict in dict.type.sys_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="assetStatus">
        <el-select v-model="queryParams.assetStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['assets:assets:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="assetsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="资产ID" align="center" prop="assetId" width="180" />
      <el-table-column label="所属种植区" align="center" prop="plantAreaId">
        <template slot-scope="scope">
          <span>{{ plantAreaMap[scope.row.plantAreaId] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="资产名称" align="center" prop="assetName" />
      <el-table-column label="分类" align="center" prop="assetCategory">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_type" :value="scope.row.assetCategory"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="assetStatus">
        <template slot-scope="scope">
          <el-tag
            :type="getStatusType(scope.row.assetStatus)"
            :style="{ backgroundColor: statusColorMap[scope.row.assetStatus], color: 'white' }"
          >
            {{ scope.row.assetStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="资产图片" align="center" prop="assetAvatar" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.assetAvatar" :width="70" :height="70"/>
        </template>
      </el-table-column>
      <el-table-column label="资产二维码" align="center" prop="assetQrCode" width="100">
        <template slot-scope="scope">
          <div v-if="scope.row.assetQrCode">
            <img :src="scope.row.assetQrCode" alt="资产二维码" style="width: 90px; height: 90px;" />
          </div>
          <div v-else>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-document"
              @click="generateQRCodeForAsset(scope.row)"
            >生成二维码</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleScrap(scope.row)"
          >报废</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 在template部分添加报废对话框 -->
    <el-dialog title="资产报废" :visible.sync="scrapDialogVisible" width="500px">
      <el-form :model="scrapForm" :rules="scrapRules" ref="scrapFormRef">
        <el-form-item label="报废原因" prop="scrapReason">
          <el-input
            type="textarea"
            v-model="scrapForm.scrapReason"
            :rows="4"
            placeholder="请输入详细的报废原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="scrapDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitScrap">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listAssets, getAssets, delAssets, addAssets, updateAssets } from "@/api/assets/assets";
import {listArea} from "@/api/region/plantarea";
import { getToken } from "@/utils/auth";
import { importTemplate } from "@/api/system/user";
import QRCode from 'qrcode'; // 引入 qrcode 库
import { requestScrap } from "@/api/assets/scrap";
export default {
  name: "Assets",
  dicts: ['sys_area', 'sys_status', 'sys_type'],
  data() {
    return {
      qrCodeImage: null, // 用于存储生成的二维码图片
      qrCodeTitle: '', // 二维码对话框标题
      qrCodeDialogVisible: false, // 二维码对话框是否显示
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 基础信息管理表格数据
      assetsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetId: null,
        plantAreaId: null,
        assetCategory: null,
        assetStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        plantAreaId: [
          { required: true, message: "所属区域不能为空", trigger: "blur" }
        ],
        assetName: [
          { required: true, message: "资产名称不能为空", trigger: "blur" }
        ],
        assetPurchaseData: [
          { required: true, message: "购置日期不能为空", trigger: "blur" }
        ],
        assetCategory: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        assetStatus: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      },
      // 种植区列表
      plantArea: [],
      //   种植区映射集合
      plantAreaMap: [],
      // 区分新增和修改逻辑
      isAdd: false,
      //原始id
      originaletAssetId: null,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/assets/assets/importData"
      },
      // 状态颜色映射
      statusColorMap: {
        '空闲中': 'green',
        '使用中': 'blue',
        '报修中': 'red',
        '维护中': '#FFA500',
        '已报废': 'gray',
        '待审核': '#FFD700'
      },
      statusMap: {
        0: '空闲中',
        1: '使用中',
        2: '报修中',
        3: '维护中',
        4: '已报废',
        5: '待审核'
      },
      // 报废相关数据
      scrapDialogVisible: false,
      scrapForm: {
        assetId: null,
        scrapReason: ""
      },
      scrapRules: {
        scrapReason: [
          { required: true, message: "请输入报废原因", trigger: "blur" },
          { min: 3, max: 200, message: "长度在3到200个字符", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getPlantAreaList()
  },
  methods: {
    /** 查询基础信息管理列表 */
    getList() {
      this.loading = true;
      return listAssets(this.queryParams)
        .then(response => {
          this.assetsList = response.rows.map(row => {
            // 假设 statusMap 是一个映射对象
            row.assetStatus = this.statusMap[row.assetStatus] || row.assetStatus;
            return row;
          });
          this.total = response.total;
          this.loading = false;
          return response; // 返回响应数据，方便调用者使用
        })
        .catch(error => {
          console.error('获取列表数据失败:', error);
          this.loading = false;
          throw error; // 抛出错误，以便调用者可以处理
        });
    },
    getPlantAreaList() {
      listArea().then(response => {
        this.plantArea = response.rows;
        this.plantAreaMap = this.plantArea.reduce((map, item) => {
          map[item.plantAreaId] = item.plantAreaName;
          return map;
        }, {});
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.isAdd = false; //重置
    },
    // 表单重置
    reset() {
      this.form = {
        assetId: null,
        plantAreaId: null,
        assetName: null,
        assetModel: null,
        assetPurchaseData: null,
        assetCategory: null,
        assetLongitude: null,
        assetLatitude: null,
        assetAltitude: null,
        assetStatus: null,
        assetIsMovable: null,
        assetManufacturer: null,
        assetAvatar: null,
        assetPurchasePrice: null,
        assetReferenceLink: null,
        assetInstallLocation: null,
        assetQrCode: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.originaletAssetId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.assetId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    handleScrap(row) {
      this.scrapDialogVisible = true;
      this.scrapForm.assetId = row.assetId;
      this.scrapForm.scrapReason = "";
    },

    submitScrap() {
      this.$refs.scrapFormRef.validate(valid => {
        if (valid) {
          requestScrap(this.scrapForm.assetId, this.scrapForm.scrapReason)
            .then(response => {
              this.$modal.msgSuccess("报废申请已提交");
              this.scrapDialogVisible = false;
              this.getList();
            })
            .catch(error => {
              console.error("报废失败:", error);
            });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.isAdd) {
            const updateData = {
              ...this.form,
              originaletAssetId: this.originaletAssetId
            };
            console.log("updateDate:"+updateData)
            console.log("修改：" + this.originaletAssetId);
            updateAssets(updateData)
              .then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                // 等待获取最新数据
                return this.getList();
              })
              .then(() => {
                const updatedAsset = this.assetsList.find(item => item.assetId === this.form.assetId);
                if (updatedAsset) {
                  // 使用最新数据重新生成二维码
                  this.generateQRCodeForAsset(updatedAsset);
                } else {
                  console.error('未在 assetsList 中找到对应设备');
                }
              })
              .catch(error => {
                console.error('更新资产信息或获取列表数据失败:', error);
              });
          } else {
            console.log("新增：" + this.originaletAssetId);
            addAssets(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const assetIds = row.assetId || this.ids;
      this.$modal.confirm('是否确认删除基础信息管理编号为"' + assetIds + '"的数据项？').then(function() {
        return delAssets(assetIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('assets/assets/export', {
        ...this.queryParams
      }, `assets_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 新增 getStatusType 方法
    getStatusType(status) {
      if (status === '空闲中') return 'success';
      if (status === '使用中') return 'primary';
      if (status === '报修中') return 'danger';
      if (status === '维护中') return 'warning';
      if (status === '已报废') return 'info';
      return ''; // 默认返回空字符串
    },
    // 生成设备专属二维码
    generateQRCodeForAsset(asset) {
      if (!asset.assetId) {
        this.$message.error('资产ID不能为空');
        return;
      }


      // 状态映射表
      const statusMap = {
        '空闲中': 0,
        '使用中': 1,
        '报修中': 2,
        '维护中': 3,
        '已报废': 4,
        '待审核': 5
      };
      // 获取当前状态对应的 long 类型值
      const longStatus = statusMap[asset.assetStatus] !== undefined ? statusMap[asset.assetStatus] : null;
      // 将二维码 URL 添加到要发送的对象中，并将 assetStatus 转换为 long 类型

      // 只包含必要的字段，并将 null 和 undefined 替换为空字符串
      const assetInfo = {
        assetId: asset.assetId || '',
        assetName: asset.assetName || '',
        assetCategory: asset.assetCategory || '',
        assetStatus: longStatus,
        plantAreaId: asset.plantAreaId || '',
      };


      // 将 assetInfo 转换为友好的文本格式
      const friendlyText = Object.entries(assetInfo)
        .map(([key, value]) => `${key}: ${value}`)
        .join('\n');

      console.log('生成二维码的文本信息:', friendlyText);

      // 生成二维码
      QRCode.toDataURL(friendlyText,{ version: 10, margin: 5, width: 350,errorCorrectionLevel: 'H'  })
        .then(url => {
          // 更新 assetsList 中对应设备的 assetQrCode 字段
          this.assetsList = this.assetsList.map(item => {
            if (item.assetId === asset.assetId) {
              return {
                ...item,
                assetQrCode: url
              };
            }
            return item;
          });

          const oliveAssets = {
            originaletAssetId: asset.assetId,
            assetQrCode: url
          };

          //调用updateAssets方法
          console.log(oliveAssets);
          updateAssets(oliveAssets);
        })
        .catch(err => {
          console.error('生成二维码失败', err);
          this.$message.error('生成二维码失败');
        });
    }
  }
};
</script>
